var express = require('express');
var router = express.Router();
const axios = require('axios');
const multer = require('multer');
const FormData = require('form-data');
const { Order } = require('../DB/ZPF');

const upload = multer({ storage: multer.memoryStorage() });

// 健康检查
router.get('/', async (req, res) => {
  res.json({ route: 'zpf', status: 'ok' });
})

// 文字转语音 TTS
// body: { text: string, voice?: string, format?: 'mp3'|'wav'|'ogg' }
router.post('/tts', async (req, res) => {
  try {
    const { text, voice = 'nova', format = 'mp3' } = req.body || {};
    if (!text) return res.status(400).json({ error: 'text is required' });

    console.log(`TTS Request: text="${text.substring(0, 100)}...", voice=${voice}, format=${format}`);
    console.log(`文本长度: ${text.length} 字符`);

    const baseURL = process.env.DIFY_OPENAI_BASE || 'http://127.0.0.1/v1';
    const apiKey = process.env.DIFY_API_KEY;

    if (!apiKey) {
      return res.status(500).json({
        error: 'no_tts_available',
        detail: 'DIFY_API_KEY 未设置',
        suggestion: '请在.env文件中设置DIFY_API_KEY'
      });
    }

    // 使用Dify的 /text-to-audio 端点
    console.log('🎯 使用Dify /text-to-audio 端点...');

    try {
      const ttsResponse = await axios.post(
        `${baseURL}/text-to-audio`,
        {
          text: text,
          format: format,
          user: 'miniapp-user'
        },
        {
          headers: { Authorization: `Bearer ${apiKey}` },
          responseType: 'arraybuffer',
          timeout: 60000,
          validateStatus: () => true
        }
      );

      if (ttsResponse.status === 200 && ttsResponse.data && ttsResponse.data.byteLength > 0) {
        console.log(`✅ Dify TTS成功！音频大小: ${ttsResponse.data.byteLength} bytes`);
        console.log(`🎵 使用Dify TTS，声音: ${voice}`);

        res.setHeader('Content-Type', `audio/${format}`);
        res.setHeader('Content-Disposition', `inline; filename="dify-speech.${format}"`);
        return res.send(Buffer.from(ttsResponse.data));
      } else {
        console.log(`⚠️ /text-to-audio 返回状态: ${ttsResponse.status}`);
        if (ttsResponse.data) {
          try {
            const errorText = ttsResponse.data.toString();
            console.log('错误详情:', errorText);
          } catch (e) {
            console.log('无法解析错误详情');
          }
        }
      }
    } catch (difyErr) {
      console.log(`❌ Dify TTS调用失败: ${difyErr.message}`);
      if (difyErr.response) {
        console.log('HTTP状态:', difyErr.response.status);
        console.log('错误详情:', difyErr.response.data);
      }
    }

    // 备选方案：使用OpenAI TTS端点
    console.log('🔄 尝试OpenAI TTS端点...');
    try {
      const openaiTtsResponse = await axios.post(
        `${baseURL}/audio/speech`,
        {
          model: 'tts-1',
          input: text,
          voice: voice
        },
        {
          headers: { Authorization: `Bearer ${apiKey}` },
          responseType: 'arraybuffer',
          timeout: 60000,
          validateStatus: () => true
        }
      );

      if (openaiTtsResponse.status === 200 && openaiTtsResponse.data && openaiTtsResponse.data.byteLength > 0) {
        console.log(`✅ OpenAI TTS成功！音频大小: ${openaiTtsResponse.data.byteLength} bytes`);
        console.log(`🎵 使用OpenAI TTS，声音: ${voice}`);

        res.setHeader('Content-Type', `audio/${format}`);
        res.setHeader('Content-Disposition', `inline; filename="openai-speech.${format}"`);
        return res.send(Buffer.from(openaiTtsResponse.data));
      }
    } catch (openaiErr) {
      console.log(`❌ OpenAI TTS失败: ${openaiErr.message}`);
    }

    // 所有TTS方案都失败
    return res.status(500).json({
      error: 'tts_all_methods_failed',
      detail: '所有TTS方法都失败了',
      triedMethods: ['Dify /text-to-audio 端点', 'OpenAI TTS端点'],
      suggestions: ['检查Dify账户余额', '确认Dify TTS配置']
    });

  } catch (err) {
    console.error('TTS error:', err);
    return res.status(500).json({
      error: 'tts_failed',
      detail: err.message
    });
  }
});

// 语音转文字 STT
// form-data: file (audio), language?: string
router.post('/stt', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) return res.status(400).json({ error: 'file is required' });

    const baseURL = process.env.DIFY_OPENAI_BASE || 'http://127.0.0.1/v1';
    const apiKey = process.env.DIFY_API_KEY;
    if (!apiKey) return res.status(500).json({ error: 'DIFY_API_KEY not set' });

    console.log(`STT Request: 文件大小 ${req.file.size} bytes, 类型 ${req.file.mimetype}`);

    // 使用Dify的 /audio-to-text 端点
    console.log('🎯 使用Dify /audio-to-text 端点...');

    try {
      const form = new FormData();
      form.append('file', req.file.buffer, {
        filename: req.file.originalname || 'audio.mp3',
        contentType: req.file.mimetype || 'audio/mpeg'
      });

      const sttResponse = await axios.post(
        `${baseURL}/audio-to-text`,
        form,
        {
          headers: {
            Authorization: `Bearer ${apiKey}`,
            ...form.getHeaders()
          },
          timeout: 60000,
          validateStatus: () => true
        }
      );

      if (sttResponse.status === 200 && sttResponse.data) {
        console.log('✅ Dify STT成功！');
        console.log('响应数据:', sttResponse.data);

        return res.json(sttResponse.data);
      } else {
        console.log(`⚠️ /audio-to-text 返回状态: ${sttResponse.status}`);
        console.log('错误详情:', sttResponse.data);

        return res.status(500).json({
          error: 'stt_failed',
          detail: `Dify STT失败: ${sttResponse.status}`,
          response: sttResponse.data
        });
      }

    } catch (difyErr) {
      console.log(`❌ Dify STT调用失败: ${difyErr.message}`);
      return res.status(500).json({
        error: 'stt_failed',
        detail: `Dify STT调用失败: ${difyErr.message}`
      });
    }

  } catch (err) {
    console.error('STT error:', err);
    return res.status(500).json({
      error: 'stt_failed',
      detail: err.message
    });
  }
});

// 文本对话流程
// body: { text: string, user?: string }
router.post('/text-chatflow', async (req, res) => {
  try {
    const { text, user = 'miniapp-user' } = req.body || {};
    if (!text) return res.status(400).json({ error: 'text is required' });

    const baseURL = process.env.DIFY_OPENAI_BASE || 'http://127.0.0.1/v1';
    const apiKey = process.env.DIFY_API_KEY;
    if (!apiKey) return res.status(500).json({ error: 'DIFY_API_KEY not set' });

    console.log(`Chat Request: text="${text}", user=${user}`);

    // 调用Dify聊天接口
    const chatPayload = {
      inputs: {
        text: text
      },
      query: text,
      response_mode: 'blocking',
      user: user,
      conversation_id: ''
    };

    const wfResp = await axios.post(`${baseURL}/chat-messages`, chatPayload, {
      headers: { Authorization: `Bearer ${apiKey}` },
      timeout: 180000, // 3分钟超时
      validateStatus: () => true
    });

    // 检查Dify响应状态
    if (wfResp.status !== 200) {
      console.log(`❌ Dify聊天失败: ${wfResp.status}`);
      console.log('错误详情:', wfResp.data);

      return res.status(500).json({
        error: 'dify_chat_failed',
        detail: `Dify聊天失败: ${wfResp.status}`,
        response: wfResp.data
      });
    }

    const chatData = wfResp.data || {};
    let replyText = chatData.answer || chatData.message || chatData.text;
    if (typeof replyText !== 'string') replyText = JSON.stringify(replyText || chatData);

    // 处理JSON格式的回复文本
    if (replyText && replyText.trim().startsWith('{') && replyText.trim().endsWith('}')) {
      console.log('🔍 检测到JSON格式回复，提取文本内容...');

      // 提取reply字段的内容
      const replyMatch = replyText.match(/"reply":\s*"([^"]*(?:\\.[^"]*)*)"/);
      if (replyMatch) {
        replyText = replyMatch[1]
          .replace(/\\n/g, '\n')  // 还原换行符
          .replace(/\\"/g, '"')   // 还原引号
          .replace(/\\\\/g, '\\'); // 还原反斜杠
        console.log('✅ 成功提取reply内容:', replyText.substring(0, 100) + '...');
      } else {
        console.log('⚠️ 未找到reply字段，使用原始文本');
      }
    }

    // 检查回复是否为空
    if (!replyText || replyText.trim() === '') {
      return res.status(500).json({
        error: 'empty_reply',
        detail: 'Dify返回的回复为空',
        suggestion: '请检查Dify工作流配置',
        chatData: chatData
      });
    }

    console.log('✅ 聊天成功，回复长度:', replyText.length);
    return res.json({ replyText });

  } catch (err) {
    console.error('text-chatflow error:', err);
    return res.status(500).json({
      error: 'text_chatflow_failed',
      detail: err.message
    });
  }
});

// 语音对话流程（完整流程：STT -> Chat -> TTS）
// form-data: file (audio), user?: string
router.post('/voice-chatflow', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) return res.status(400).json({ error: 'file is required' });

    const baseURL = process.env.DIFY_OPENAI_BASE || 'http://127.0.0.1/v1';
    const apiKey = process.env.DIFY_API_KEY;
    if (!apiKey) return res.status(500).json({ error: 'DIFY_API_KEY not set' });

    console.log(`Voice Chatflow: 文件大小 ${req.file.size} bytes, 类型 ${req.file.mimetype}`);

    // 1) STT: 语音 -> 文本
    console.log('🎯 步骤1: 语音转文本...');
    const sttForm = new FormData();
    sttForm.append('file', req.file.buffer, {
      filename: req.file.originalname || 'audio.mp3',
      contentType: req.file.mimetype || 'audio/mpeg'
    });

    const sttResp = await axios.post(`${baseURL}/audio-to-text`, sttForm, {
      headers: {
        Authorization: `Bearer ${apiKey}`,
        ...sttForm.getHeaders()
      },
      timeout: 60000,
      validateStatus: () => true
    });

    if (sttResp.status !== 200 || !sttResp.data) {
      console.log(`❌ STT失败: ${sttResp.status}`);
      return res.status(500).json({
        error: 'stt_failed',
        detail: `语音转文本失败: ${sttResp.status}`,
        response: sttResp.data
      });
    }

    const sttData = sttResp.data || {};
    const transcript = sttData.text || sttData.result || sttData.data?.text || sttData.data?.result || '';
    if (!transcript) {
      return res.status(500).json({
        error: 'empty_transcript',
        detail: '语音转文本结果为空',
        sttResponse: sttData
      });
    }

    console.log(`✅ STT成功，转录文本: "${transcript}"`);

    // 2) Chat: 文本 -> 答复
    console.log('🎯 步骤2: 文本对话...');
    const chatPayload = {
      inputs: {
        text: transcript
      },
      query: transcript,
      response_mode: 'blocking',
      user: req.body.user || 'miniapp-user',
      conversation_id: ''
    };

    const chatResp = await axios.post(`${baseURL}/chat-messages`, chatPayload, {
      headers: { Authorization: `Bearer ${apiKey}` },
      timeout: 120000,
      validateStatus: () => true
    });

    if (chatResp.status !== 200 || !chatResp.data) {
      console.log(`❌ 聊天失败: ${chatResp.status}`);
      return res.status(500).json({
        error: 'chat_failed',
        detail: `文本对话失败: ${chatResp.status}`,
        response: chatResp.data
      });
    }

    const chatData = chatResp.data || {};
    let replyText = chatData.answer || chatData.message || chatData.text;
    if (typeof replyText !== 'string') {
      replyText = JSON.stringify(replyText || chatData);
    }

    if (!replyText) {
      return res.status(500).json({
        error: 'empty_reply',
        detail: '对话回复为空',
        chatResponse: chatData
      });
    }

    console.log(`✅ 聊天成功，回复: "${replyText.substring(0, 100)}..."`);

    // 用户可选择仅返回文本
    if (req.body.returnText === 'true') {
      return res.json({ transcript, replyText });
    }

    // 3) TTS: 答复文本 -> 音频
    console.log('🎯 步骤3: 文本转语音...');

    try {
      const ttsResponse = await axios.post(
        `${baseURL}/text-to-audio`,
        {
          text: replyText,
          format: 'mp3',
          user: req.body.user || 'miniapp-user'
        },
        {
          headers: { Authorization: `Bearer ${apiKey}` },
          responseType: 'arraybuffer',
          timeout: 30000,
          validateStatus: () => true
        }
      );

      if (ttsResponse.status === 200 && ttsResponse.data && ttsResponse.data.byteLength > 0) {
        console.log(`✅ TTS成功，音频大小: ${ttsResponse.data.byteLength} bytes`);

        res.setHeader('Content-Type', 'audio/mp3');
        res.setHeader('Content-Disposition', 'inline; filename="voice-reply.mp3"');
        return res.send(Buffer.from(ttsResponse.data));
      } else {
        console.log(`❌ TTS失败: ${ttsResponse.status}`);
        return res.status(500).json({
          error: 'tts_failed',
          detail: `文本转语音失败: ${ttsResponse.status}`
        });
      }

    } catch (ttsErr) {
      console.log(`❌ TTS调用失败: ${ttsErr.message}`);
      return res.status(500).json({
        error: 'tts_failed',
        detail: `TTS调用失败: ${ttsErr.message}`
      });
    }

  } catch (err) {
    console.error('voice-chatflow error:', err);
    return res.status(500).json({
      error: 'voice_chatflow_failed',
      detail: err.message
    });
  }
});

// 创建维修订单
router.post('/create-order', async (req, res) => {
  try {
    const { name, phone, deviceType, problem, address } = req.body;

    // 验证必填字段
    if (!name || !phone || !deviceType || !problem) {
      return res.status(400).json({
        success: false,
        message: '请填写完整的必填信息'
      });
    }

    // 创建新订单
    const newOrder = new Order({
      customerInfo: {
        name: name.trim(),
        phone: phone.trim(),
        address: address ? address.trim() : ''
      },
      deviceInfo: {
        type: deviceType.trim(),
        problem: problem.trim()
      }
    });

    // 保存订单到数据库
    const savedOrder = await newOrder.save();

    res.json({
      success: true,
      message: '订单创建成功',
      data: {
        orderNumber: savedOrder.orderNumber,
        orderId: savedOrder._id,
        status: savedOrder.status,
        createdAt: savedOrder.createdAt
      }
    });

  } catch (error) {
    console.error('创建订单失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，订单创建失败',
      error: error.message
    });
  }
});

// 查询订单详情
router.get('/order/:orderNumber', async (req, res) => {
  try {
    const { orderNumber } = req.params;

    const order = await Order.findOne({ orderNumber });

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    res.json({
      success: true,
      data: order
    });

  } catch (error) {
    console.error('查询订单失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，查询订单失败',
      error: error.message
    });
  }
});

// 根据订单号查询单个订单
router.get('/orders/:orderNumber', async (req, res) => {
  try {
    const { orderNumber } = req.params;

    const order = await Order.findOne({ orderNumber });

    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    res.json({
      success: true,
      data: order
    });

  } catch (error) {
    console.error('查询订单失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，查询订单失败',
      error: error.message
    });
  }
});

// 查询用户的所有订单
router.get('/orders/phone/:phone', async (req, res) => {
  try {
    const { phone } = req.params;

    const orders = await Order.find({ 'customerInfo.phone': phone })
      .sort({ createdAt: -1 }); // 按创建时间倒序

    res.json({
      success: true,
      data: orders
    });

  } catch (error) {
    console.error('查询用户订单失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，查询订单失败',
      error: error.message
    });
  }
});

// 更新订单状态
router.put('/order/:orderNumber/status', async (req, res) => {
  try {
    const { orderNumber } = req.params;
    const { status } = req.body;

    // 验证状态值
    const validStatuses = ['pending', 'confirmed', 'in_progress', 'completed', 'cancelled'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        message: '无效的订单状态'
      });
    }

    const updatedOrder = await Order.findOneAndUpdate(
      { orderNumber },
      { status, updatedAt: new Date() },
      { new: true }
    );

    if (!updatedOrder) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    res.json({
      success: true,
      message: '订单状态更新成功',
      data: updatedOrder
    });

  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，更新订单状态失败',
      error: error.message
    });
  }
});

module.exports = router;

// 获取所有订单（管理员用）
router.get('/orders', async (req, res) => {
  try {
    const { page = 1, limit = 10, status, search } = req.query;

    let query = {};

    // 状态筛选
    if (status) {
      query.status = status;
    }

    // 搜索功能
    if (search) {
      query.$or = [
        { orderNumber: { $regex: search, $options: 'i' } },
        { 'customerInfo.name': { $regex: search, $options: 'i' } },
        { 'customerInfo.phone': { $regex: search, $options: 'i' } },
        { 'deviceInfo.type': { $regex: search, $options: 'i' } }
      ];
    }

    const orders = await Order.find(query)
      .sort({ createdAt: -1 })
      .limit(limit * 1)
      .skip((page - 1) * limit);

    const total = await Order.countDocuments(query);

    res.json({
      success: true,
      data: orders,
      pagination: {
        current: parseInt(page),
        pageSize: parseInt(limit),
        total: total
      }
    });

  } catch (error) {
    console.error('获取所有订单失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，获取订单失败',
      error: error.message
    });
  }
});

// 更新订单详情
router.put('/order/:orderNumber', async (req, res) => {
  try {
    const { orderNumber } = req.params;
    const updateData = req.body;

    const updatedOrder = await Order.findOneAndUpdate(
      { orderNumber },
      { ...updateData, updatedAt: new Date() },
      { new: true }
    );

    if (!updatedOrder) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    res.json({
      success: true,
      message: '订单更新成功',
      data: updatedOrder
    });

  } catch (error) {
    console.error('更新订单失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，更新订单失败',
      error: error.message
    });
  }
});

// 删除订单
router.delete('/order/:orderNumber', async (req, res) => {
  try {
    const { orderNumber } = req.params;

    const deletedOrder = await Order.findOneAndDelete({ orderNumber });

    if (!deletedOrder) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    res.json({
      success: true,
      message: '订单删除成功'
    });

  } catch (error) {
    console.error('删除订单失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，删除订单失败',
      error: error.message
    });
  }
});

// 确认订单
router.put('/order/:orderNumber/confirm', async (req, res) => {
  try {
    const { orderNumber } = req.params;
    const { cost, paid = false } = req.body;

    // 构建更新数据
    const updateData = {
      status: 'confirmed',
      updatedAt: new Date()
    };

    // 如果提供了费用，则更新费用
    if (cost !== undefined && cost !== null) {
      updateData.cost = parseFloat(cost);
    }

    // 如果提供了支付状态，则更新支付状态
    if (paid !== undefined) {
      updateData.paid = paid;
    }

    const updatedOrder = await Order.findOneAndUpdate(
      { orderNumber },
      updateData,
      { new: true }
    );

    if (!updatedOrder) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    res.json({
      success: true,
      message: '订单确认成功',
      data: updatedOrder
    });

  } catch (error) {
    console.error('确认订单失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，确认订单失败',
      error: error.message
    });
  }
});

// 取消订单
router.put('/order/:orderNumber/cancel', async (req, res) => {
  try {
    const { orderNumber } = req.params;
    const { reason } = req.body;

    const updatedOrder = await Order.findOneAndUpdate(
      { orderNumber },
      {
        status: 'cancelled',
        updatedAt: new Date(),
        notes: reason ? `取消原因：${reason}` : '订单已取消'
      },
      { new: true }
    );

    if (!updatedOrder) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    res.json({
      success: true,
      message: '订单取消成功',
      data: updatedOrder
    });

  } catch (error) {
    console.error('取消订单失败:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误，取消订单失败',
      error: error.message
    });
  }
});

// 支付订单接口
router.post('/pay-order', async (req, res) => {
  try {
    const { orderNumber, paymentMethod = 'wechat', amount } = req.body;

    console.log(`支付订单请求: ${orderNumber}, 支付方式: ${paymentMethod}, 金额: ${amount}`);

    // 验证必要参数
    if (!orderNumber) {
      return res.status(400).json({
        success: false,
        message: '订单号不能为空'
      });
    }

    // 查找订单
    const order = await Order.findOne({ orderNumber });
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }

    // 检查订单状态
    if (order.status === 'cancelled') {
      return res.status(400).json({
        success: false,
        message: '订单已取消，无法支付'
      });
    }

    if (order.paid) {
      return res.status(400).json({
        success: false,
        message: '订单已支付'
      });
    }

    // 验证支付金额
    if (amount && amount !== order.cost) {
      return res.status(400).json({
        success: false,
        message: `支付金额不匹配，应支付: ${order.cost}元`
      });
    }

    // 模拟支付处理（实际项目中需要对接真实支付接口）
    // 这里简化处理，直接标记为已支付
    order.paid = true;
    order.paymentMethod = paymentMethod;
    order.paidAt = new Date();
    order.updatedAt = new Date();

    // 如果订单状态是待确认，支付后自动确认
    if (order.status === 'pending') {
      order.status = 'confirmed';
    }

    await order.save();

    res.json({
      success: true,
      message: '支付成功',
      data: {
        orderNumber: order.orderNumber,
        amount: order.cost,
        paymentMethod: order.paymentMethod,
        paidAt: order.paidAt,
        status: order.status
      }
    });

  } catch (error) {
    console.error('支付订单失败:', error);
    res.status(500).json({
      success: false,
      message: '支付处理失败',
      error: error.message
    });
  }
});

// 手动清理已完成订单
router.post('/cleanup-completed-orders', async (req, res) => {
  try {
    const { cleanupCompletedOrders } = require('../cleanup-orders');
    const deletedCount = await cleanupCompletedOrders();

    res.json({
      success: true,
      message: `成功清理了 ${deletedCount} 条已完成的订单`,
      data: {
        deletedCount
      }
    });
  } catch (error) {
    console.error('手动清理订单失败:', error);
    res.status(500).json({
      success: false,
      message: '清理订单失败',
      error: error.message
    });
  }
}); 